package com.sy.common.util;

import com.alibaba.fastjson.JSONObject;
import com.gok.pay.wx.SignType;
import com.gok.pay.wx.WXPayConstants;
import com.gok.pay.wx.WXPayUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sy.cloud.wechat.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

/**
 * Created by mac on 2017/11/30.
 */
@Slf4j
public class Funutil {
    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public static String encodeByMD5(String originString) {
        if (originString != null) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] results = md.digest(originString.getBytes());
                String resultString = byteArrayToHexString(results);
                return resultString.toLowerCase();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 转换字节数组为16进制字串
     *
     * @param b 字节数组
     * @return 十六进制字串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    /**
     * 将一个字节转化成16进制形式的字符串
     *
     * @param b
     * @return
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }


    /**
     * 发送短信
     */

    public static void send_newsms(String phone, String randomcode) {
        HttpUtils utils = new HttpUtils();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", "N3176154");
        jsonObject.put("password", "yUqjeDJgYC482a");
        jsonObject.put("msg", "【萌鲨互娱】您的验证码是：" + randomcode);
        jsonObject.put("phone", phone);

        String url = "http://smssh1.253.com/msg/send/json"; //提交的url地址

        String resp = utils.post(jsonObject.toJSONString(), url);
        log.info(resp);
    }

    public static String getOrdersn() {
        long a1 = System.currentTimeMillis();
        String a2 = a1 + "";
        String a3 = a2.substring(1, 13);

        Random random = new Random();
        int a4 = random.nextInt(100);
        String a5 = "";
        if (a4 < 10) {
            a5 = "0" + a4;
        } else {
            a5 = "" + a4;
        }

        String a6 = a3 + a5;
        return a6;
    }

    public static String cardIfActive(String cardno, String req) throws Exception {

        String key = "3eced11b140c44a4be53561adf92acf8";
        String url = "http://scpay.shopping98.com/v1/gateway.shtml";
//  也支持中文
        String nonce_str = WXPayUtil.generateUUID();


        Map<String, String> map = new HashMap<String, String>();
        map.put("service", "v1_liquidation_bankcard_query");
        map.put("version", "1.0");
        map.put("merchant_no", "676988092351791104");
        map.put("charset", "UTF-8");
        map.put("req_time", req);
        map.put("sign_type", "MD5");
        map.put("nonce_str", nonce_str);
        map.put("card_no", cardno);
        String sign = WXPayUtil.generateSignature2(map, "3eced11b140c44a4be53561adf92acf8", SignType.MD5);
        map.put("sign", sign);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            params.add(entry.getKey(), entry.getValue());
        }

        String result = restRequest(url, params);
        Gson gson = new Gson();
        Map<String, String> maps = gson.fromJson(result, new TypeToken<Map<String, String>>() {
        }.getType());
        return maps.get("head_code");
    }

    public static String restRequest(String url, MultiValueMap<String, String> params) {
        return restRequest(url, params, null);
    }

    public static String restRequest(String url, MultiValueMap<String, String> params, Map<String, String> otherParams) {
        RestTemplate client = new RestTemplate();
        client.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.parseMediaType("application/x-www-form-urlencoded;charset=UTF-8"));
        if (otherParams != null) {
            if (otherParams.get(HttpHeaders.REFERER) != null) {
                headers.set(HttpHeaders.REFERER, otherParams.get(HttpHeaders.REFERER));
            }
        }

        headers.set(HttpHeaders.REFERER, "https://mma.qq.com/mqqactivity/cgi/starmap/get_online");

        //  封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);

        if (otherParams != null) {
            //  执行HTTP请求
            ResponseEntity<String> response1 = client.exchange(url, HttpMethod.GET, requestEntity, String.class);
            return response1.getBody();
            //  输出结果
        } else {
            //  执行HTTP请求
            ResponseEntity<String> response1 = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
            return response1.getBody();
            //  输出结果
        }
    }


    // sha1加密
    public static String generateSignature(final Map<String, String> data) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        String s = sb.substring(0, sb.length() - 1);
//        return DigestUtils.sha1Hex(sb.toString());
        return encode(s);
    }

    /**
     * 生成 sha加密
     *
     * @param
     * @param
     * @return 加密结果
     * @throws Exception
     */
    public static String encode(String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(str.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String getFormattedText(byte[] bytes) {
        char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
                '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

}
